package com.xsh.daw;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileUtils {

    /**
     * 复制文件
     * @param srcFile  源文件路径
     * @param destFile 目标文件路径
     * @return 是否复制成功
     */
    public static boolean copyFile(String srcFile, String destFile,CopyCallback callback) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            File dest = new File(destFile);
            // 如果目标目录不存在则创建
            File parent = dest.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            inputStream = new FileInputStream(srcFile);
            //outputStream = new FileOutputStream(destFile);
            File f = new File(srcFile);
            String a = f.getName();
            //Log.d("FileUtils",a);
            outputStream = new FileOutputStream(destFile + "/" + a);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            return true;
        } catch (IOException e) {
            //e.printStackTrace()
            //e.getMessage();//
            String erroeMsg = e.getMessage();
            String errorType = e.getClass().getName();
            String stackTrace = Log.getStackTraceString(e);
            Log.e("FileUtils","IOException: " + erroeMsg);
            Log.e("FileUtils","Error type: " + erroeMsg);
            Log.e("FileUtils","StackTrace: " + erroeMsg);
           // if(callback!=null){callback.onComplete(false,e.getMessage());}
            return false;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static boolean copyFile(String srcFile, String destFile) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            File dest = new File(destFile);
            // 如果目标目录不存在则创建
            File parent = dest.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            inputStream = new FileInputStream(srcFile);
            outputStream = new FileOutputStream(destFile);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            return true;
        } catch (IOException e) {
            //e.printStackTrace();

            return false;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*public static void copyFilesTo(String srcDir,String targetDir)
    {
        /*File srcDir1 = new File(srcDir);
        srcDir*/
   // }
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void copyDirectory(String sourcePath, String targetPath) throws IOException {
        Path src = Paths.get(sourcePath);
        Path dest = Paths.get(targetPath);

        // 创建目标目录（如果不存在）
        Files.createDirectories(dest);

        // 递归复制核心逻辑
        Files.walk(src).forEach(source -> {
            try {
                Path target = dest.resolve(src.relativize(source));
                System.out.println("Copying: " + source + " -> " + target);

                if (Files.isDirectory(source)) {
                    Files.createDirectories(target);
                } else {
                    Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (IOException e) {
                System.err.println("Failed to copy: " + source);
                e.printStackTrace();
            }
        });
    }
    /**
     * 仅复制源目录下的所有文件（不处理子目录）
     * @param sourceDir 源目录路径
     * @param targetDir 目标目录路径
     */
    // 复制代码在真机安卓13有问题 模拟器安卓5.x测试通过
    public static void copyFilesOnly(String sourceDir, String targetDir,CopyCallback callback) throws IOException {
        File src = new File(sourceDir);
        File dest = new File(targetDir);

        // 校验源目录合法性
        if (!src.exists() || !src.isDirectory()) {
            throw new IllegalArgumentException("无效的源目录路径");
        }

        // 创建目标目录（若不存在）
        if (!dest.exists() && !dest.mkdirs()) {
            throw new IOException("无法创建目标目录: " + dest.getAbsolutePath());
        }

        // 获取源目录下所有文件（过滤掉子目录）
        File[] files = src.listFiles(file -> file.isFile());

        if (files == null) return; // 空目录直接返回

        // 遍历并复制文件
        for (File file : files) {
            File targetFile = new File(dest, file.getName());
            try {
                copyFileWithChannel(file, targetFile);
            }catch(IOException e)
            {
                if(callback != null) callback.onComplete(false,"复制失败: " +e.getMessage());
                throw e;
            }
        }
        if(callback!= null) callback.onComplete(true,"成功复制" + files.length +"个文件");
    }

    /**
     * 使用FileChannel高效复制单个文件（支持覆盖）
     */
    private static void copyFileWithChannel(File source, File dest) throws IOException {
        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(dest);
             FileChannel inChannel = fis.getChannel();
             FileChannel outChannel = fos.getChannel()) {

            // 覆盖已存在文件
            inChannel.transferTo(0, inChannel.size(), outChannel);
        }
    }

}